package com.xy.cloud.filter;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.xy.cloud.constant.CacheConstants;
import com.xy.cloud.constant.HttpStatus;
import com.xy.cloud.constant.TokenConstants;

import com.xy.cloud.properties.IgnoreWhiteProperties;
import com.xy.cloud.properties.RequestsProperties;
import com.xy.cloud.service.RedisService;
import com.xy.cloud.utils.ServletUtils;
import com.xy.cloud.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * 网关鉴权
 *
 * @author ruoyi
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    private static final Logger log = LoggerFactory.getLogger(AuthFilter.class);

    @Autowired
    private RedisService redisService;

    /**
     * 校验重复提交properties
     */
    @Autowired
    private RequestsProperties requestsProperties;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpRequest.Builder mutate = request.mutate();
        String path = request.getURI().getPath();
        String ipAddress = ServletUtils.webFluxGetIpAddress(request);

  /*      boolean match = StringUtils.matches(path,requestsProperties.getPaths());
        if (match) {
            //定义redis防重复提交的key，格式 requests:ip:uriPath
            String requestKey = StringUtils.format("{}:{}:{}", CacheConstants.DUPLICATE_REQUESTS_PREFIX, ipAddress, path);
            Boolean sb = redisService.setNx(requestKey, RandomUtil.randomNumbers(1), requestsProperties.getTime());
            if (!sb) {
                return ServletUtils.webFluxResponseWriter(exchange.getResponse(), "重复提交", HttpStatus.ERROR);
            }
        }*/
        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }

    private void addHeader(ServerHttpRequest.Builder mutate, String name, Object value) {
        if (value == null) {
            return;
        }
        String valueStr = value.toString();
        String valueEncode = ServletUtils.urlEncode(valueStr);
        mutate.header(name, valueEncode);
    }

    private void removeHeader(ServerHttpRequest.Builder mutate, String name) {
        mutate.headers(httpHeaders -> httpHeaders.remove(name)).build();
    }

    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String msg) {
        log.error("[鉴权异常处理]请求路径:{}", exchange.getRequest().getPath());
        return ServletUtils.webFluxResponseWriter(exchange.getResponse(), msg, HttpStatus.UNAUTHORIZED);
    }

    @Override
    public int getOrder() {
        return -200;
    }




}